package com.service.impl;

import com.entity.Component;
import com.exception2.CodeMirrorException;
import com.repository.ComponentRepository;
import com.request.ComponentRequest;
import com.response.ComponentResponse;
import com.service.ComponentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ComponentServiceImpl implements ComponentService {
    @Autowired
    private ComponentRepository componentRepository;
    @Override
    public ComponentResponse save(ComponentRequest componentRequest) {
        String handle = componentRequest.getHandle();
        if(StringUtils.isEmpty(handle)){
            throw new CodeMirrorException("请填写handle");
        }
        Component component = null;
        if(componentRequest.getId() != null || componentRequest.getId() != 0){
            component = componentRepository.getOne(componentRequest.getId());
        }


        switch (handle){
            case "add":
                this.checkName(componentRequest.getComponentName());
                componentRequest.setCrDate(componentRequest.getDate());
                componentRequest.setCrUser(componentRequest.getUserName());
                componentRequest.setCrId(componentRequest.getUserId());
                component = componentRepository.save(componentRequest);
                break;
            case "update":

                this.checkId(componentRequest.getId());
                this.checkName(componentRequest.getComponentName());
                componentRequest.setMoDate(componentRequest.getDate());
                componentRequest.setMoUser(componentRequest.getUserName());
                component = componentRepository.save(componentRequest);
                break;
            case "query":
                break;
            case "del":
                componentRepository.deleteById(componentRequest.getId());
                component = null;
        }
        ComponentResponse componentResponse = (ComponentResponse) component;
        return componentResponse;
    }
    private void checkId(Integer id){
        if(id == null || id  == 0){
            throw new CodeMirrorException("请填写id");
        }
    }

    private void checkName(String name){
        Component component = componentRepository.findByComponentName(name);
        if(component != null ){
            throw new CodeMirrorException(String.format("%s已存在",component.getComponentName()));
        }
    }
}
